package com.example.Sao.MyActivity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.Sao.Adapter.QRcodeListAdpter;
import com.example.Sao.Data.LogInfo;
import com.example.Sao.MyFragment.SuccesDialog;
import com.example.Sao.ObjectBox.DeviceEntity;
import com.example.Sao.ObjectBox.DeviceEntity_;
import com.example.Sao.R;
import com.example.Sao.Serivce.SerialPortService;
import com.example.Sao.SqlLite.SQLiteDB;
import com.example.Sao.Tools.GlideUtil;
import com.example.Sao.Tools.ObjectBoxHelper;
import com.example.Sao.Tools.SharedPrefsUtil;
import com.example.Sao.Tools.StatusColorUtil;
import com.google.gson.Gson;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import io.reactivex.functions.Consumer;

import static com.example.Sao.MyActivity.MyApplication.getContext;

public class StartActivity extends MyBaseActivity implements OnClickListener{
	private ObjectBoxHelper objectBoxHelper;
	private String status;
	private ImageView iv_back;
	private TextView title;
	private LinearLayout sao1;
	private static final String TAG = "StartActivity";
	//部门名称
	private String partment;
	private static int IMAGE_HALFWIDTH = 50;//宽度值，影响中间图片大小
	private String path_result = "/sdcard/ScanResult";
	public static final int MESSAGE_RECEIVER_DATA = 1 ;
	private RecyclerView recyclerView;
	private QRcodeListAdpter qRcodeListAdpter;
	private MHandler mHandler;

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_start);
		Log.d(TAG, "onCreate");
		//设置状态栏颜色
		StatusColorUtil.setColor(this, getResources().getColor(R.color.skyblue));
		initViews();
		objectBoxHelper = ObjectBoxHelper.getInstance();
		IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(SerialPortService.BARCODEPORT_RECEIVEDDATA_ACTION);
        registerReceiver(receiver, intentFilter);
        objectBoxHelper = ObjectBoxHelper.getInstance();
        mHandler = new MHandler(this);
	}

	/**绑定页面数据
	 * @param intent
	 */
	private void initdata(Intent intent){
	    Bundle bundle= intent.getExtras();
		status =bundle.getStringArray("status")[0];
		title.setText(status);
		recyclerView.setLayoutManager(new LinearLayoutManager(this));
		if ("扫码盘点".equals(status)){
			//获取其他页面传递的部门名称
			partment = bundle.getStringArray("status")[1];
             List<String>codelist = new ArrayList<>();
			objectBoxHelper.RxQuery("user", DeviceEntity_.username)
			.subscribe(new Consumer<List<DeviceEntity>>() {
				@Override
				public void accept(List<DeviceEntity> o) throws Exception {
					for (DeviceEntity entity:o){
						//Time为空对象说明该设备还未盘点
						if (entity.isStaus()) {
							codelist.add(entity.getDeviceStreamCode());
						}
					}
					initAnim(recyclerView);
					if (qRcodeListAdpter==null) {
						qRcodeListAdpter = new QRcodeListAdpter(codelist, StartActivity.this);
						recyclerView.setAdapter(qRcodeListAdpter);
					}else {
						qRcodeListAdpter.setQRcodeList(codelist);
						qRcodeListAdpter.notifyDataSetChanged();
					}
				}
			});
		}else {
			List<String>codelist = new ArrayList<>();
			objectBoxHelper.RxQuery("qrcode", DeviceEntity_.username)
					.subscribe(new Consumer<List<DeviceEntity>>() {
						@Override
						public void accept(List<DeviceEntity> o) throws Exception {
							for (DeviceEntity entity:o){
								//Time为空对象说明该设备还未盘点
								codelist.add(entity.getDeviceStreamCode());
							}
							initAnim(recyclerView);
							if (qRcodeListAdpter==null) {
								qRcodeListAdpter = new QRcodeListAdpter(codelist, StartActivity.this);
								recyclerView.setAdapter(qRcodeListAdpter);
							}else {
								qRcodeListAdpter.setQRcodeList(codelist);
								qRcodeListAdpter.notifyDataSetChanged();
							}
						}
					});
		}

	}

	/**
	 * 绑定控件
	 */
	private void initViews(){
		recyclerView  =findViewById(R.id.RecyclerView);
		title = findViewById(R.id.mytitle);
		sao1 = findViewById(R.id.sao1);
		iv_back = findViewById(R.id.iv_back);
		iv_back.setOnClickListener(this::onClick);
	}

	@Override
	protected void onResume() {
		super.onResume();
		initdata(getIntent());
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(receiver);
	}

	/**
     * 广播接收器
     * */
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(action!=null){
                if(action.equals(SerialPortService.BARCODEPORT_RECEIVEDDATA_ACTION)){
                    String data=intent.getStringExtra(SerialPortService.BARCODEPORT_RECEIVEDDATA_EXTRA_DATA);
                    if(data!=null&&"扫码盘点".equals(status)){
						//弹出数据展示窗口
						final SuccesDialog succesDialog = new SuccesDialog();
						//设置上下文
						succesDialog.setmContext(StartActivity.this);
						//设置扫码结果
						succesDialog.setDeviceStreamCode(data);
						//设置当前部门
						succesDialog.setPartment(partment);
						//内部查询回调监听
						succesDialog.setSuccesDialogLinster(new SuccesDialog.SuccesDialogLinster() {
							@Override
							public void SuccesDialogLinster(final boolean isSucces) {
								//弹出框消失延时
								new Handler().postDelayed(new Runnable() {
									@Override
									public void run() {
										//查询结果正确及退出
										if (isSucces) {
											StartActivity.this.finish();
										}else {
											//查询结果不对等待动画结束并退出
											new Handler().postDelayed(new Runnable() {
												@Override
												public void run() {
													StartActivity.this.finish();
												}
											},2000);
										}
									}
								},800);
							}
						});
						//展示弹出窗
						succesDialog.show(getSupportFragmentManager(),"");
                    }else if (data!=null&&"扫码出库".equals(status)){
                    	Message message = new Message();
						message.what=1;
						message.obj = data;
                    	mHandler.handleMessage(message);
					}else {
                    	Toast.makeText(StartActivity.this,"未扫描到二维码",Toast.LENGTH_SHORT).show();
					}
                }
            }
        }
    };
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.setting, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.settings) {
			Intent mIntent = new Intent(this,SettingsActivity.class);
			startActivity(mIntent);
			return true;
		}else if(id == R.id.symbologies){
			
	  		SharedPreferences mSP = getSharedPreferences(MyApplication.SYMBOL_CONFIG_SIG, 0);
  	  		boolean isSig =  mSP.getBoolean(MyApplication.SCAN_MODE_SIG,false);
  
  	  		Intent mIntent = new Intent(this,isSig ? SymbologiesSig.class : SymbologiesQR.class); 
			this.startActivity(mIntent);
			return true;
		}else if(id == R.id.about){
			Intent mIntent = new Intent(this,AboutActivity.class);
			this.startActivity(mIntent);
			return true;
		}else if(id == R.id.export){
			//WriteExcelFile.write(getFilesDir()+"/scan_result.xls");
//			ExcelOperator.createFolder(path_result);
//			ExcelOperator.write(this,path_result+"/scan_result.xls");
//			Toast.makeText(this, "The result had export to " + path_result, Toast.LENGTH_LONG).show();
			return true;
		}
		
		return super.onOptionsItemSelected(item);
	}
 
	@Override
	public void onClick(View v) {
		switch(v.getId()){
			case R.id.iv_back:
				this.finish();
				break;
		default:
			break;
		}
		
	}
	/**
	 * 生成带logo的二维码，logo默认为二维码的1/5
	 *
	 * @param text    需要生成二维码的文字、网址等
	 * @param size    需要生成二维码的大小（）
	 * @param mBitmap logo文件
	 * @return bitmap
	 */
	public  Bitmap createQRCodeWithLogo(String text, int size, Bitmap mBitmap) {
		try {
			IMAGE_HALFWIDTH = size / 10;
			Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
			/*
			 * 设置容错级别，默认为ErrorCorrectionLevel.L
			 * 因为中间加入logo所以建议你把容错级别调至H,否则可能会出现识别不了
			 */
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
			//设置空白边距的宽度
			hints.put(EncodeHintType.MARGIN, 1); //default is 4
			// 图像数据转换，使用了矩阵转换
			BitMatrix bitMatrix = new QRCodeWriter().encode(text,
					BarcodeFormat.QR_CODE, size, size, hints);

			int width = bitMatrix.getWidth();//矩阵高度
			int height = bitMatrix.getHeight();//矩阵宽度
			int halfW = width / 2;
			int halfH = height / 2;

			Matrix m = new Matrix();
			float sx = (float) 2 * IMAGE_HALFWIDTH / mBitmap.getWidth();
			float sy = (float) 2 * IMAGE_HALFWIDTH
					/ mBitmap.getHeight();
			m.setScale(sx, sy);
			//设置缩放信息
			//将logo图片按martix设置的信息缩放
			mBitmap = Bitmap.createBitmap(mBitmap, 0, 0,
					mBitmap.getWidth(), mBitmap.getHeight(), m, false);

			int[] pixels = new int[size * size];
			for (int y = 0; y < size; y++) {
				for (int x = 0; x < size; x++) {
					if (x > halfW - IMAGE_HALFWIDTH && x < halfW + IMAGE_HALFWIDTH
							&& y > halfH - IMAGE_HALFWIDTH
							&& y < halfH + IMAGE_HALFWIDTH) {
						//该位置用于存放图片信息
						//记录图片每个像素信息
						pixels[y * width + x] = mBitmap.getPixel(x - halfW
								+ IMAGE_HALFWIDTH, y - halfH + IMAGE_HALFWIDTH);
					} else {
						if (bitMatrix.get(x, y)) {
							pixels[y * size + x] = 0xff000000;
						} else {
							pixels[y * size + x] = 0xffffffff;
						}
					}
				}
			}
			Bitmap bitmap = Bitmap.createBitmap(size, size,
					Bitmap.Config.ARGB_8888);
			bitmap.setPixels(pixels, 0, size, 0, 0, size, size);
			return bitmap;
		} catch (WriterException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 弱引用handler
	 */
	private class MHandler extends Handler {
		private WeakReference<Activity> reference;
		public MHandler(Activity activity) {
			// 使用WeakReference弱引用持有Activity实例
			reference = new WeakReference<Activity>(activity);
		}
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case 1:
					Toast.makeText(StartActivity.this,"扫码成功",Toast.LENGTH_SHORT).show();
					String data  = String.valueOf(msg.obj);
					DeviceEntity deviceEntity = new DeviceEntity();
					deviceEntity.setUsername("qrcode");
					deviceEntity.setDeviceStreamCode(data.replaceAll("\r|\n", ""));
					objectBoxHelper.RxAdd(deviceEntity);
					try {
						Thread.sleep(200);
					}catch (InterruptedException e){
						e.printStackTrace();
					}
					List<String>codelist = new ArrayList<>();
					objectBoxHelper.RxQuery("qrcode", DeviceEntity_.username)
							.subscribe(new Consumer<List<DeviceEntity>>() {
								@Override
								public void accept(List<DeviceEntity> o) throws Exception {
									for (DeviceEntity deviceEntity1:o){
										codelist.add(deviceEntity1.getDeviceStreamCode());
									}
									initAnim(recyclerView);
									if (qRcodeListAdpter==null) {
										qRcodeListAdpter = new QRcodeListAdpter(codelist, StartActivity.this);
										recyclerView.setAdapter(qRcodeListAdpter);
									}else {
										qRcodeListAdpter.setQRcodeList(codelist);
										qRcodeListAdpter.notifyDataSetChanged();
									}
								}
							});
					break;
				default:
			}
		}
	}
	//设置动画效果
	private void initAnim(RecyclerView list) {
		//通过加载XML动画设置文件来创建一个Animation对象；
		Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.item_anim);
		//得到一个LayoutAnimationController对象；
		LayoutAnimationController lac = new LayoutAnimationController(animation);
		//设置控件显示的顺序；
		lac.setOrder(LayoutAnimationController.ORDER_NORMAL);
		//设置控件显示间隔时间；
		lac.setDelay(0.3f);
		//为ListView设置LayoutAnimationController属性；
		list.setLayoutAnimation(lac);
	}
}
